﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CRM.Database.Model
{
    public partial class TrainingsCourses : IGetKeyValue, IGetNamesValues
    {
        #region Implementation of IGetKeyValue

        /// <summary>
        /// Получение ключего значения элемента
        /// </summary>
        /// <returns>Ключевое значение</returns>
        public int GetKeyValue()
        {
            return IdTrainingsCourse;
        }

        #endregion

        #region Extended properties

        /// <summary>
        /// Локализованный список аудиторий через запятую
        /// </summary>
        private string _auditoriums;

        /// <summary>
        /// Список типов через запятую
        /// </summary>
        private string _courseTypes;

        /// <summary>
        /// Локализованный список площадок через запятую
        /// </summary>
        private string _places;

        /// <summary>
        /// Список тренеров через запятую
        /// </summary>
        private string _trainers;

        /// <summary>
        /// Имя рубрики
        /// </summary>
        public string RubricName
        {
            get { return Rubrics != null ? Rubrics.NameRu : ""; }
        }

        /// <summary>
        /// Список тренеров через запятую
        /// </summary>
        public string Trainers
        {
            get
            {
                if (!string.IsNullOrEmpty(_trainers))
                    return _trainers;
                var result = new List<string>();
                foreach (TrainingsCoursesTrainers item in TrainingsCoursesTrainers)
                {
                    if (IdTrainingsCourse == item.IdTrainingsCourse)
                    {
                        var trainersCol = new TrainingsTrainersCollection();
                        result.Add(((TrainingsTrainers) trainersCol.GetItemById(item.IdTrainingsTrainer)).Name);
                        //result.Add(DB.GetTrainingsTrainerbyId(item.IdTrainingsTrainer).Name);
                    }
                }
                string resultString = "";
                foreach (string item in result)
                {
                    if (resultString.Length == 0)
                        resultString = resultString + item;
                    else
                        resultString = resultString + ";" + item;
                }
                return resultString;
            }

            set { _trainers = value; }
        }

        /// <summary>
        /// Список типов через запятую
        /// </summary>
        public string CourseTypes
        {
            get
            {
                if (!string.IsNullOrEmpty(_courseTypes))
                    return _courseTypes;
                var result = new List<string>();
                foreach (TrainingsCoursesAndTypes item in TrainingsCoursesAndTypes)
                {
                    if (IdTrainingsCourse == item.IdTrainingsCourse)
                    {
                        var typesCol = new TrainingCoursesTypesCollection();
                        result.Add(((TrainingCoursesTypes) typesCol.GetItemById(item.IdTraningCoursesType)).NameRu);
                        //result.Add(DB.GetTrainingCoursesTypebyId(item.IdTraningCoursesType).NameRu);
                    }
                }
                string resultString = "";
                foreach (string item in result)
                {
                    if (resultString.Length == 0)
                        resultString = resultString + item;
                    else
                        resultString = resultString + ";" + item;
                }
                return resultString;
            }

            set { _courseTypes = value; }
        }

        /// <summary>
        /// Локализованный список площадок через запятую
        /// </summary>
        public string Places
        {
            get
            {
                if (!string.IsNullOrEmpty(_places))
                    return _places;
                var result = new List<string>();
                foreach (TrainingsCoursesPlaces item in TrainingsCoursesPlaces)
                {
                    if (IdTrainingsCourse != item.IdTrainingsCourse) continue;
                    var placesCol = new TrainingsPlacesCollection();
                    var place = (TrainingsPlaces) placesCol.GetItemById(item.IdTrainingsPlace);
                    if (place != null)
                    {
                        result.Add(place.GetLocalizedName());
                    }
                }
                string resultString = "";
                foreach (string item in result)
                {
                    if (resultString.Length == 0)
                        resultString = resultString + item;
                    else
                        resultString = resultString + ";" + item;
                }
                return resultString;
            }
            set { _places = value; }
        }

        /// <summary>
        /// Локализованный список аудиторий через запятую
        /// </summary>
        public string Auditoriums
        {
            get
            {
                if (!string.IsNullOrEmpty(_auditoriums))
                    return _auditoriums;
                var result = new List<string>();
                foreach (TrainingsCoursesAuditoriums item in TrainingsCoursesAuditoriums)
                {
                    if (IdTrainingsCourse != item.IdTrainingsCourse) continue;
                    var auditoriumsCol = new TrainingsAuditoriumsCollection();
                    var auditorium = (TrainingsAuditoriums) auditoriumsCol.GetItemById(item.IdTrainingsAuditorium);
                    if (auditorium != null)
                    {
                        result.Add(auditorium.GetLocalizedName());
                    }
                }
                string resultString = "";
                foreach (string item in result)
                {
                    if (resultString.Length == 0)
                        resultString = resultString + item;
                    else
                        resultString = resultString + ";" + item;
                }
                return resultString;
            }
            set { _auditoriums = value; }
        }

        /// <summary>
        /// Свойство для отображения списка аудиторий в ячейке таблицы
        /// </summary>
        public string AuditoriumsColumn
        {
            get
            {
                var result = new List<string>();
                foreach (TrainingsCoursesAuditoriums item in TrainingsCoursesAuditoriums)
                {
                    if (IdTrainingsCourse != item.IdTrainingsCourse) continue;
                    var auditoriumsCol = new TrainingsAuditoriumsCollection();
                    var auditorium = (TrainingsAuditoriums) auditoriumsCol.GetItemById(item.IdTrainingsAuditorium);
                    if (auditorium != null)
                    {
                        result.Add(auditorium.GetLocalizedName());
                    }
                }
                string resultString = "";
                foreach (string item in result)
                {
                    if (resultString.Length == 0)
                        resultString = resultString + item;
                    else
                        resultString = resultString + Environment.NewLine + item;
                }
                return resultString;
            }
            //set { _auditoriums = value; }
        }

        /// <summary>
        /// Свойство для отображения списка площадок в ячейке таблицы
        /// </summary>
        public string PlacesColumn
        {
            get
            {
                var result = new List<string>();
                foreach (TrainingsCoursesPlaces item in TrainingsCoursesPlaces)
                {
                    if (IdTrainingsCourse != item.IdTrainingsCourse) continue;
                    var placesCol = new TrainingsPlacesCollection();
                    var place = (TrainingsPlaces) placesCol.GetItemById(item.IdTrainingsPlace);
                    if (place != null)
                    {
                        result.Add(place.GetLocalizedName());
                    }
                }
                string resultString = "";
                foreach (string item in result)
                {
                    if (resultString.Length == 0)
                        resultString = resultString + item;
                    else
                        resultString = resultString + Environment.NewLine + item;
                }
                return resultString;
            }
            set { _places = value; }
        }

        /// <summary>
        /// Текстовое поле для ссылки
        /// </summary>
        public string LinkText
        {
            get { return "Подать заявку"; }
        }

        /// <summary>
        /// Свойство для отображения списка тренеров в ячейке таблицы
        /// </summary>
        public string TrainersColumn
        {
            get
            {
                var result = new List<string>();
                foreach (TrainingsCoursesTrainers item in TrainingsCoursesTrainers)
                {
                    if (IdTrainingsCourse == item.IdTrainingsCourse)
                    {
                        var trainersCol = new TrainingsTrainersCollection();
                        result.Add(((TrainingsTrainers) trainersCol.GetItemById(item.IdTrainingsTrainer)).Name);
                        //result.Add(DB.GetTrainingsTrainerbyId(item.IdTrainingsTrainer).Name);
                    }
                }
                string resultString = "";
                foreach (string item in result)
                {
                    if (resultString.Length == 0)
                        resultString = resultString + item;
                    else
                        resultString = resultString + Environment.NewLine + item;
                }
                return resultString;
            }
        }

        /// <summary>
        /// отображение информации в колонке типов курсов
        /// </summary>
        public string CourseTypesColumn
        {
            get
            {
                var result = new List<string>();
                foreach (TrainingsCoursesAndTypes item in TrainingsCoursesAndTypes)
                {
                    if (IdTrainingsCourse == item.IdTrainingsCourse)
                    {
                        var typesColumn = new TrainingCoursesTypesCollection();
                        result.Add(
                            ((TrainingCoursesTypes) typesColumn.GetItemById(item.IdTraningCoursesType)).LocalizedName);
                        //result.Add(DB.GetTrainingCoursesTypebyId(item.IdTraningCoursesType).NameRu);
                    }
                }
                string resultString = "";
                foreach (string item in result)
                {
                    if (resultString.Length == 0)
                        resultString = resultString + item;
                    else
                        resultString = resultString + Environment.NewLine + item;
                }
                return resultString;
            }

            set { _courseTypes = value; }
        }

        /// <summary>
        /// Плановый?
        /// </summary>
        public bool IsPlanned
        {
            get { return ValidateCourseType(1); }
        }

        /// <summary>
        /// Выездной?
        /// </summary>
        public bool IsRemote
        {
            get { return ValidateCourseType(2); }
        }

        /// <summary>
        /// Вебинар?
        /// </summary>
        public bool IsWebinar
        {
            get { return ValidateCourseType(3); }
        }

        /// <summary>
        /// возвращает true если курс содержит заданный тип
        /// </summary>
        /// <param name="courseType"></param>
        /// <returns></returns>
        private bool ValidateCourseType(int courseType)
        {
            if (TrainingsCoursesAndTypes != null)
            {
                return
                    TrainingsCoursesAndTypes.Where(item => item != null).Any(
                        item => item.IdTraningCoursesType == courseType);
            }
            return false;
        }

        /// <summary>
        /// Продолжительность курса для формирования календаря
        /// </summary>
        public double DurationForScheduler
        {
            get
            {
                if (Duration < 0.5)
                    return 0.3;
                return Duration - 0.3;
            }
        }

        #endregion

        /// <summary>
        /// Добавляет привязку тренера к курсу
        /// </summary>
        /// <param name="trainer"></param>
        /// <param name="user"></param>
        public bool AddTrainer(TrainingsTrainers trainer, string user)
        {
            if (trainer != null)
            {
                var bindingCol = new TrainingsCoursesTrainersCollection();
                foreach (TrainingsCoursesTrainers item in bindingCol.TrainingsCoursesTrainersList)
                {
                    if (item.IdTrainingsCourse == IdTrainingsCourse &&
                        item.IdTrainingsTrainer == trainer.IdTrainingsTrainer)
                        return false;
                }
                var bindingItem = new TrainingsCoursesTrainers
                                      {
                                          IdTrainingsCourse = IdTrainingsCourse,
                                          IdTrainingsTrainer = trainer.IdTrainingsTrainer
                                      };
                bindingCol.Add(bindingItem, user);
            }
            return true;
        }

        /// <summary>
        /// Удаляет привязку тренера к курсу
        /// </summary>
        /// <param name="trainer"></param>
        public bool DeleteTrainer(TrainingsTrainers trainer)
        {
            var bindingCol = new TrainingsCoursesTrainersCollection();
            if (trainer != null)
            {
                foreach (TrainingsCoursesTrainers item in bindingCol.TrainingsCoursesTrainersList)
                {
                    if (item.IdTrainingsCourse == IdTrainingsCourse &&
                        item.IdTrainingsTrainer == trainer.IdTrainingsTrainer)
                        return bindingCol.Delete(item);
                }
            }
            return false;
        }

        /// <summary>
        /// Добавление списка тренеров
        /// </summary>
        /// <param name="trainersList"></param>
        /// <param name="user"></param>
        public bool AddTrainersList(List<TrainingsTrainers> trainersList, string user)
        {
            if (trainersList == null) return false;
            if (trainersList.Count < 1) return false;
            foreach (TrainingsTrainers trainer in trainersList)
            {
                AddTrainer(trainer, user);
            }
            return true;
        }

        /// <summary>
        /// Обновление привязанного списка тренеров
        /// </summary>
        /// <param name="trainersListUpdated"></param>
        /// <param name="user"></param>
        public bool UpdateTrainersList(List<TrainingsTrainers> trainersListUpdated, string user)
        {
            var trainersCol = new TrainingsTrainersCollection();
            if (trainersListUpdated == null) return false;
            //получение старого списка тренеров
            List<TrainingsTrainers> trainersList = trainersCol.GetTrainersListByCourse(this);
            if (trainersList == null) return false;
            //добавление новых тренеров к списку, если они там отсутствуют
            foreach (TrainingsTrainers item in trainersListUpdated)
            {
                // if (!trainersList.Contains(item))
                if (trainersList.FirstOrDefault(c => c.IdTrainingsTrainer == item.IdTrainingsTrainer) == null)
                {
                    AddTrainer(item, user);
                }
            }
            //Удаление тренеров, которых нет в обновленном списке
            foreach (TrainingsTrainers item in trainersList)
            {
                //  if (!trainersListUpdated.Contains(item))
                if (trainersListUpdated.FirstOrDefault(c => c.IdTrainingsTrainer == item.IdTrainingsTrainer) == null)
                {
                    DeleteTrainer(item);
                }
            }
            return true;
        }


        /// <summary>
        /// Добавляет привязку площадки к курсу
        /// </summary>
        /// <param name="place"></param>
        /// <param name="user"></param>
        public bool AddPlace(TrainingsPlaces place, string user)
        {
            if (place != null)
            {
                var bindingCol = new TrainingsCoursesPlacesCollection();
                foreach (TrainingsCoursesPlaces item in bindingCol.TrainingsCoursesPlacesList)
                {
                    if (item.IdTrainingsCourse == IdTrainingsCourse && item.IdTrainingsPlace == place.IdTrainingsPlace)
                        return false;
                }
                var bindingItem = new TrainingsCoursesPlaces
                                      {
                                          IdTrainingsCourse = IdTrainingsCourse,
                                          IdTrainingsPlace = place.IdTrainingsPlace
                                      };
                bindingCol.Add(bindingItem, user);
            }
            return true;
        }

        /// <summary>
        /// Удаляет привязку площадки к курсу
        /// </summary>
        /// <param name="place"></param>
        public bool DeletePlace(TrainingsPlaces place)
        {
            var bindingCol = new TrainingsCoursesPlacesCollection();
            if (place != null)
            {
                foreach (TrainingsCoursesPlaces item in bindingCol.TrainingsCoursesPlacesList)
                {
                    if (item.IdTrainingsCourse == IdTrainingsCourse && item.IdTrainingsPlace == place.IdTrainingsPlace)
                        return bindingCol.Delete(item);
                }
            }
            return false;
        }

        /// <summary>
        /// Добавление списка площадок
        /// </summary>
        /// <param name="placesList"></param>
        /// <param name="user"></param>
        public bool AddPlacesList(List<TrainingsPlaces> placesList, string user)
        {
            if (placesList == null) return false;
            if (placesList.Count < 1) return false;
            foreach (TrainingsPlaces place in placesList)
            {
                AddPlace(place, user);
            }
            return true;
        }

        /// <summary>
        /// Обновление привязанного списка тренеров
        /// </summary>
        /// <param name="placesListUpdated"></param>
        /// <param name="user"></param>
        public bool UpdatePlacesList(List<TrainingsPlaces> placesListUpdated, string user)
        {
            var placesCol = new TrainingsPlacesCollection();
            if (placesListUpdated == null) return false;
            //получение старого списка тренеров
            List<TrainingsPlaces> placesList = placesCol.GetPlacesListByCourse(this);
            if (placesList == null) return false;
            //добавление новых тренеров к списку, если они там отсутствуют
            foreach (TrainingsPlaces place in placesListUpdated)
            {
                //if (!placesList.Contains(place))
                if (placesList.FirstOrDefault(p => p.IdTrainingsPlace == place.IdTrainingsPlace) == null)
                {
                    AddPlace(place, user);
                }
            }
            //Удаление тренеров, которых нет в обновленном списке
            foreach (TrainingsPlaces item in placesList)
            {
                //if (!placesListUpdated.Contains(item))
                if (placesListUpdated.FirstOrDefault(p => p.IdTrainingsPlace == item.IdTrainingsPlace) == null)
                {
                    DeletePlace(item);
                }
            }
            return true;
        }


        /// <summary>
        /// Добавляет привязку аудитории к курсу
        /// </summary>
        /// <param name="auditorium"></param>
        /// <param name="user"></param>
        public bool AddAuditorium(TrainingsAuditoriums auditorium, string user)
        {
            if (auditorium != null)
            {
                var bindingCol = new TrainingsCoursesAuditoriumsCollection();
                foreach (TrainingsCoursesAuditoriums item in bindingCol.TrainingsCoursesAuditoriumsList)
                {
                    if (item.IdTrainingsCourse == IdTrainingsCourse &&
                        item.IdTrainingsAuditorium == auditorium.IdTrainingsAuditorium)
                        return false;
                }
                var bindingItem = new TrainingsCoursesAuditoriums
                                      {
                                          IdTrainingsCourse = IdTrainingsCourse,
                                          IdTrainingsAuditorium = auditorium.IdTrainingsAuditorium
                                      };
                bindingCol.Add(bindingItem, user);
            }
            return true;
        }

        /// <summary>
        /// Удаляет привязку аудитории к курсу
        /// </summary>
        /// <param name="auditorium"></param>
        public bool DeleteAuditorium(TrainingsAuditoriums auditorium)
        {
            var bindingCol = new TrainingsCoursesAuditoriumsCollection();
            if (auditorium != null)
            {
                foreach (TrainingsCoursesAuditoriums item in bindingCol.TrainingsCoursesAuditoriumsList)
                {
                    if (item.IdTrainingsCourse == IdTrainingsCourse &&
                        item.IdTrainingsAuditorium == auditorium.IdTrainingsAuditorium)
                        return bindingCol.Delete(item);
                }
            }
            return false;
        }

        /// <summary>
        /// Добавление списка аудиторий
        /// </summary>
        /// <param name="auditoriumsList"></param>
        /// <param name="user"></param>
        public bool AddAuditoriumsList(List<TrainingsAuditoriums> auditoriumsList, string user)
        {
            if (auditoriumsList == null) return false;
            if (auditoriumsList.Count < 1) return false;
            foreach (TrainingsAuditoriums item in auditoriumsList)
            {
                AddAuditorium(item, user);
            }
            return true;
        }

        /// <summary>
        /// Обновление привязанного списка аудиторий
        /// </summary>
        /// <param name="auditoriumsListUpdated"></param>
        /// <param name="user"></param>
        public bool UpdateAuditoriumsList(List<TrainingsAuditoriums> auditoriumsListUpdated, string user)
        {
            var auditoriumsCol = new TrainingsAuditoriumsCollection();
            if (auditoriumsListUpdated == null) return false;
            //получение старого списка тренеров
            List<TrainingsAuditoriums> auditoriumsList = auditoriumsCol.GetAuditoriumsListByCourse(this);
            if (auditoriumsList == null) return false;
            //добавление новых тренеров к списку, если они там отсутствуют
            foreach (TrainingsAuditoriums item in auditoriumsListUpdated)
            {
                //if (!auditoriumsList.Contains(item))
                if (auditoriumsList.FirstOrDefault(p => p.IdTrainingsAuditorium == item.IdTrainingsAuditorium) == null)
                {
                    AddAuditorium(item, user);
                }
            }
            //Удаление тренеров, которых нет в обновленном списке
            foreach (TrainingsAuditoriums item in auditoriumsList)
            {
                //if (!auditoriumsListUpdated.Contains(item))
                if (auditoriumsListUpdated.FirstOrDefault(p => p.IdTrainingsAuditorium == item.IdTrainingsAuditorium) ==
                    null)
                {
                    DeleteAuditorium(item);
                }
            }
            return true;
        }


        /// <summary>
        /// Добавляет привязку типа к курсу
        /// </summary>
        /// <param name="type"></param>
        /// <param name="user"></param>
        public bool AddType(TrainingCoursesTypes type, string user)
        {
            if (type != null)
            {
                var bindingCol = new TrainingsCoursesAndTypesCollection();
                foreach (TrainingsCoursesAndTypes item in bindingCol.TrainingsCoursesAndTypesList)
                {
                    if (item.IdTrainingsCourse == IdTrainingsCourse &&
                        item.IdTraningCoursesType == type.IdTrainingCoursesType)
                        return false;
                }
                var bindingItem = new TrainingsCoursesAndTypes
                                      {
                                          IdTrainingsCourse = IdTrainingsCourse,
                                          IdTraningCoursesType = type.IdTrainingCoursesType
                                      };
                bindingCol.Add(bindingItem, user);
            }
            return true;
        }

        /// <summary>
        /// Удаляет привязку типа к курсу
        /// </summary>
        /// <param name="type"></param>
        public bool DeleteType(TrainingCoursesTypes type)
        {
            var bindingCol = new TrainingsCoursesAndTypesCollection();
            if (type != null)
            {
                foreach (TrainingsCoursesAndTypes item in bindingCol.TrainingsCoursesAndTypesList)
                {
                    if (item.IdTrainingsCourse == IdTrainingsCourse &&
                        item.IdTraningCoursesType == type.IdTrainingCoursesType)
                        return bindingCol.Delete(item);
                }
            }
            return false;
        }

        /// <summary>
        /// Добавление списка типов
        /// </summary>
        /// <param name="typesList"></param>
        /// <param name="user"></param>
        public bool AddTypesList(List<TrainingCoursesTypes> typesList, string user)
        {
            if (typesList == null) return false;
            if (typesList.Count < 1) return false;
            foreach (TrainingCoursesTypes item in typesList)
            {
                AddType(item, user);
            }
            return true;
        }

        /// <summary>
        /// Обновление привязанного списка тренеров
        /// </summary>
        /// <param name="typesListUpdated"></param>
        /// <param name="user"></param>
        public bool UpdateTypesList(List<TrainingCoursesTypes> typesListUpdated, string user)
        {
            var typesCol = new TrainingCoursesTypesCollection();
            if (typesListUpdated == null) return false;
            //получение старого списка тренеров
            List<TrainingCoursesTypes> typesList = typesCol.GetTrainingsCoursesTypesByCourseId(IdTrainingsCourse);
            if (typesList == null) return false;
            //добавление новых тренеров к списку, если они там отсутствуют
            foreach (TrainingCoursesTypes item in typesListUpdated)
            {
                if (!typesList.Contains(item))
                {
                    AddType(item, user);
                }
            }
            //Удаление тренеров, которых нет в обновленном списке
            foreach (TrainingCoursesTypes item in typesList)
            {
                if (!typesListUpdated.Contains(item))
                {
                    DeleteType(item);
                }
            }
            return true;
        }

        #region Implementation of IGetNamesValues

        /// <summary>
        /// Получение списка имён
        /// </summary>
        /// <returns>Список имён</returns>
        public List<string> GetNamesValues()
        {
            var list = new List<string>();
            list.Add(Name);
            return list;
        }

        #endregion

        #region Extended methods

        /// <summary>
        /// Заполнить пропущнные значения пробелами
        /// </summary>
        public void Fill()
        {
            if (string.IsNullOrEmpty(this.Name))
                this.Name = " ";
            if (string.IsNullOrEmpty(this.LinkToMaterial))
                this.LinkToMaterial = " ";
            if (string.IsNullOrEmpty(this.LinkToProgramm))
                this.LinkToProgramm = " ";
            if (string.IsNullOrEmpty(this.LinkToFeedBack))
                this.LinkToFeedBack = " ";
            if (string.IsNullOrEmpty(this.Description))
                this.Description = " ";
            
        }

        #endregion
    }
}